﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Text.RegularExpressions;
using System.Net;

namespace HtmlFileDownloader
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void mnuTest1_Click(object sender, RoutedEventArgs e)
        {
            DockPanel dock = new DockPanel();
            tabItem2.Content = dock;

            for (int i = 0; i < 17; i++)
            {
                Button btn = new Button();
                btn.Content = "Button No." + (i + 1);
                dock.Children.Add(btn);

                btn.SetValue(DockPanel.DockProperty, (Dock)(i % 4));
            }
        }

        private void itemTemplate_Click(object sender, RoutedEventArgs e)
        {
            string source = txtHtml.Text;

            string linkPattern = @"<link[^>]+href=\s*(?:'(?<href>[^']+)'|""(?<href>[^""]+)""|(?<href>[^>\s]+))\s*[^>]*>";
            string scriptPattern = @"<script[^>]+src=\s*(?:'(?<src>[^']+)'|""(?<src>[^""]+)""|(?<src>[^>\s]+))\s*[^>]*>";

            Regex regex = new Regex(linkPattern, RegexOptions.IgnoreCase);

            StringBuilder sb = new StringBuilder("");

            foreach (Match match in GetMatches(linkPattern, source))
            {
                ////sb.Append(match.Value).Append(System.Environment.NewLine);

                //foreach (Capture capture in match.Captures)
                //{
                //    string s = capture.Value;
                //}

                //foreach (Group group in match.Groups)
                //{
                //    //string s = group.Value;
                //    sb.Append(group.Value).Append(System.Environment.NewLine);
                //}
                if (match.Groups.Count > 1)
                {
                    sb.Append(match.Groups[1].Value).Append(System.Environment.NewLine);

                    DownloadFile(match.Groups[1].Value);
                }

            }
            sb.Append(System.Environment.NewLine);

            foreach (Match match in GetMatches(scriptPattern, source))
            {
                ////sb.Append(match.Value).Append(System.Environment.NewLine);
                //foreach (Group group in match.Groups)
                //{
                //    //string s = group.Value;
                //    sb.Append(group.Value).Append(System.Environment.NewLine);

                //    //DownloadFile(group.Value);
                //}
                if (match.Groups.Count > 1)
                {
                    sb.Append(match.Groups[1].Value).Append(System.Environment.NewLine);
                    DownloadFile(match.Groups[1].Value);
                }
            }

            txtUrls.Text = sb.ToString();
        }

        
        private void downHtmlImg_Click(object sender, RoutedEventArgs e)
        {
            string source = txtHtml.Text;

            string linkPattern = @"<link[^>]+href=\s*(?:'(?<href>[^']+)'|""(?<href>[^""]+)""|(?<href>[^>\s]+))\s*[^>]*>";
            string scriptPattern = @"<script[^>]+src=\s*(?:'(?<src>[^']+)'|""(?<src>[^""]+)""|(?<src>[^>\s]+))\s*[^>]*>";
            string achorHref = @"<a[^>]+href=\s*(?:'(?<href>[^']+)'|""(?<href>[^""]+)""|(?<href>[^>\s]+))\s*[^>]*>(?<text>.*?)</a>";
            string achorHref2 = @"(?<=href="")[\s\S]*?(?="" )";
            string imgPattern = @"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>";

            string imgPatternA = @"(?<=<img )[\s\S]*?(?=>)";
            string imgPatternB = @"(?<=src[\s]*=[\s]*""?)[\s\S]*?(?=""? )";


            Regex regex = new Regex(imgPattern, RegexOptions.IgnoreCase);
            StringBuilder sb = new StringBuilder("");

            foreach (Match match in GetMatches(imgPattern, source))
            {
                if (match.Groups.Count > 1)
                {
                    sb.Append(match.Groups[1].Value).Append(System.Environment.NewLine);
                    DownloadFile(match.Groups[1].Value);
                }
            }
            //sb.Append(System.Environment.NewLine);

            //foreach (Match match in GetMatches(scriptPattern, source))
            //{
            //    if (match.Groups.Count > 1)
            //    {
            //        sb.Append(match.Groups[1].Value).Append(System.Environment.NewLine);
            //        DownloadFile(match.Groups[1].Value);
            //    }
            //}
            txtUrls.Text = sb.ToString();
        }

        private static MatchCollection GetMatches(string pattern, string originalText)
        {
            Regex tmpRegex = new Regex(pattern, RegexOptions.IgnoreCase);
            MatchCollection matches = tmpRegex.Matches(originalText);

            return matches;
        }

        private void DownloadFile(string url)
        {
            if(url == null || url.Length == 0)
            {
                return;
            }
            url = url.Trim().Trim('\'').Trim('\"');//.Trim('.');

            url = FixUpUrl(txtBaseUrl.Text, url);

            if (url.StartsWith("/"))
            {
                url = txtBaseUrl.Text + url;
            }
            if (!url.StartsWith("http://"))
                return;

            string filename = url;
            if (filename.LastIndexOf("/") > -1)
            {
                filename = url.Substring(url.LastIndexOf("/") + 1);
            }
            if (filename.IndexOf('?') == 0)
            {
                filename = "untitle.txt";
            }
            if (filename.IndexOf('?') > 0)
            {
                filename = filename.Substring(0, filename.IndexOf('?'));
            }
            WebClient fileReader = new WebClient();
            
            string path = AppDomain.CurrentDomain.BaseDirectory + "images" + "\\";
            if(!System.IO.Directory.Exists( path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            if (!System.IO.File.Exists(path + filename))
            {
                try
                {
                    fileReader.DownloadFile(url, path + filename);
                }
                catch (HttpListenerException ex)
                {
                }
                catch (Exception except)
                {
                }
            }
            else
            {

            }
        }

        private void image_Click(object sender, RoutedEventArgs e)
        {
            string source = txtHtml.Text;
            //string imgPattern = @"url([^)]+)";

            string imgPattern = "(?<=url\\u0028)[^\\u0029]+(?=\\u0029)";
            

            //Regex regex = new Regex(linkPattern, RegexOptions.IgnoreCase);

            StringBuilder sb = new StringBuilder("");

            foreach (Match match in GetMatches(imgPattern, source))
            {
                if (match.Groups.Count > 0)
                {
                    sb.Append(match.Groups[0].Value).Append(System.Environment.NewLine);

                    DownloadFile(match.Groups[0].Value);
                    txtUrls.AppendText(FixUpUrl(txtBaseUrl.Text, match.Groups[0].Value));
                    txtUrls.AppendText(System.Environment.NewLine);
                }
            }
            //txtUrls.Text = sb.ToString();
        }

        public static string FixUpUrl(string baseUrl, string originalUrl)
        {

            if (originalUrl == null || originalUrl.Length == 0)
                return originalUrl;
            if (baseUrl == null || baseUrl.Length == 0)
                return originalUrl;
            if (originalUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
                return originalUrl;

            if (!baseUrl.EndsWith("/"))
            {
                baseUrl += "/";
            }

            string tmp = baseUrl.Substring(0, baseUrl.LastIndexOf('/'));

            if (baseUrl.StartsWith("http://") && baseUrl.EndsWith("/"))
            {
                tmp = baseUrl.Trim('/');
            }

            if (originalUrl[0] == '/')
            {
                if (baseUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
                {
                    return baseUrl.Substring(0, baseUrl.IndexOf('/', 7)) + originalUrl;
                }
                else
                {
                    return "http://" + baseUrl.Substring(0, baseUrl.IndexOf('/')) + originalUrl;
                }
            }

            if (originalUrl[0] == '.')
            {
                if (originalUrl[1] == '.')
                {
                    while (originalUrl.StartsWith("../"))
                    {
                        originalUrl = originalUrl.Substring(3);
                        tmp = tmp.Substring(0, tmp.LastIndexOf('/'));
                    }
                    return tmp + "/" + originalUrl;
                }
                else
                {
                    return tmp + originalUrl.Substring(1);
                }
            }

            
            return tmp + "/" + originalUrl;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Res.ResWindow frm = new Res.ResWindow();
            frm.Owner = this;
            frm.Show();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            ItemCollection items = lstBox.Items;

            items.Add("ddd");
        }

        private void Regex_Click(object sender, RoutedEventArgs e)
        {
             //string imgPattern = "(?<=url\\u0028)[^\\u0029]+(?=\\u0029)";
            //string imgPattern = "(?<=" + txtStart.Text + ")[^" + txtBaseUrl.Text + "]+(?=\\u0029)";

            String pattern = "(?<={0})[^{1}]+(?={2})";

            string source = txtHtml.Text;
            //string imgPattern = @"url([^)]+)";

            string imgPattern = String.Format(pattern, txtStart.Text, txtEnd.Text, txtNot.Text);// "(?<=url\\u0028)[^\\u0029]+(?=\\u0029)";
            //Regex regex = new Regex(linkPattern, RegexOptions.IgnoreCase);
            txtUrls.AppendText(imgPattern);

            StringBuilder sb = new StringBuilder("");

            foreach (Match match in GetMatches(imgPattern, source))
            {
                if (match.Groups.Count > 0)
                {
                    sb.Append(match.Groups[0].Value).Append(System.Environment.NewLine);

                    DownloadFile(match.Groups[0].Value.TrimStart('='));
                    txtUrls.AppendText(FixUpUrl(txtBaseUrl.Text, match.Groups[0].Value));
                    txtUrls.AppendText(System.Environment.NewLine);
                }
            }
        }
    }
}
